# figure_1.R
rm(list = ls())
setwd("/Users/John/Dropbox/")

# --- Load Packages --- 
library(readxl)
library(tidyverse)
library(cowplot)

# --- Load and reshape datasets --- 
or <- read_excel("JOP_Replication_Materials/data/raw/dv_clean.xlsx", sheet = "ownership_restrictions") %>%
  pivot_longer(cols = 7:12, names_to = NULL, values_to = "isic")

lcr <- read_excel("JOP_Replication_Materials/data/raw/dv_clean.xlsx", sheet = "local_content_requirements") %>%
  pivot_longer(cols = 7:13, names_to = NULL, values_to = "isic")

gp <- read_excel("JOP_Replication_Materials/data/raw/dv_clean.xlsx", sheet = "government_procurement") %>%
  pivot_longer(cols = 7:11, names_to = NULL, values_to = "isic")

# --- Combine and summarize --- 
combined <- bind_rows(or, lcr, gp) %>%
  filter(!is.na(isic)) %>%
  group_by(type, year) %>%
  summarise(type_year = n_distinct(desc_chinese), .groups = "drop") %>%
  group_by(year) %>%
  summarise(total_year = sum(type_year), .groups = "drop") %>%
  filter(year >= 1995 & year <= 2014)

# --- Plot --- 
fig1 <- ggplot(combined, aes(x = year, y = total_year)) +
  geom_bar(stat = "identity", fill = "grey70") +
  theme_minimal(base_size = 12) +
  theme(
    axis.text.x = element_text(size = 10),
    axis.title.x = element_blank(),
    axis.text.y = element_text(size = 10),
    axis.title.y = element_blank(),
    legend.position = "none",
    plot.title = element_blank()
  )

# --- Save figure --- 
ggsave(
  filename = "JOP_Replication_Materials/output/figures/figure_1.pdf",
  plot = fig1,
  width = 8.5, height = 5.5
)

message("✅ Saved figure to: JOP_Replication_Materials/output/figures/figure_1.pdf")
browseURL("JOP_Replication_Materials/output/figures/figure_1.pdf")
